package com.kongt.utils;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
 
/**分页工具类   
 * @author kongt 2017年10月23日
 *
 */
public class PageUtil {
 
	/**
	 * 页码字段名称
	 */
	private final static String PAGEINDEX_FIELD_NAME="pageIndex";
	
    /**
     * 总数
     */
    private int total;  
 
    /**
     * 每页显示数
     */
    private int pageSize=10;  
    
 
    /**
     * 访问的url
     */
    private String url;  
    
   
    /**
     * 记忆参数
     */
    private Map<String,Object> keys;    
    
 
    /**
     * 当前页数
     */
    private int pageIndex=1; 
    
 
    /**
     * 当前页数
     */
    private int pageCount;   

    /**
     * 构造传参数
     * @param total
     * @param element
     * @param url
     * @param keys
     * @param p
     */
    public PageUtil(HttpServletRequest requst,int pageIndex,int pageSize,int total){ 
        this.total = total;
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;  
        this.url =  requst.getScheme() + "://" + requst.getServerName()
        + ":" + requst.getServerPort() + requst.getContextPath()
        + "/";
        this.keys = getRequestMap(requst); 
        if(this.total != 0 && this.total%this.pageSize == 0){
            this.pageCount = this.total/this.pageSize;
        }else{
            this.pageCount = this.total/this.pageSize+1;
        }
    }
    
    
    
	/**获得参数Map集合
	 * @param requst request请求
	 * @return 参数key-valueMap
	 */
	public Map<String, Object> getRequestMap(HttpServletRequest requst) {
		Map<String, Object> paraMaps = new HashMap<String, Object>(1024);
		final Map<String, String[]> requestMaps =requst.getParameterMap();
		if (requestMaps != null && requestMaps.size() > 0) {
			for (Map.Entry<String, String[]> item : requestMaps.entrySet()) {
				String key = item.getKey();
				String value = "";
				if (item.getValue() != null && item.getValue().length > 0) {
					value = item.getValue()[0];
				}
				paraMaps.put(key, value);
			}
		} 
		return paraMaps;
	}
    
    
    
    
    /**
     * 拼接分页访问的url
     * @param p
     * @param keys
     * @return 拼接好的带参数url
     */
    private String createFullUrl(int pageIndex,Map<String,Object> keys){
        StringBuffer buf = new StringBuffer(this.url).append("?"); 
        if(keys.containsKey(PAGEINDEX_FIELD_NAME)){
        	keys.remove(PAGEINDEX_FIELD_NAME);
        	keys.put(PAGEINDEX_FIELD_NAME, pageIndex);
        }
        if(keys != null){
            buf.append(this.createParamUrl(keys));
        }
        return buf.toString();
    }
    
    /**
     * 参数的url形式（"&dhgks=12&..."）
     * @param keys
     * @return 拼接好的参数url
     */
    private String createParamUrl(Map<String,Object> keys){
        StringBuffer buf = new StringBuffer();
        
        if(keys != null){
            for(String key : keys.keySet()){
                buf.append(key+"="+keys.get(key)).append("&");
            }
            return buf.toString();
        }else{
            return "";
        }
        
    }
    
    /**
     * 生成分页代码
     * @return
     */
    public String showPage(){
       
        if(this.total>0){
        	 StringBuffer buf = new StringBuffer(" <ul class=\"pagination\" id=\"pagination\">");
        	  buf.append("<li class=\"first\" ><a href=\""+this.createFullUrl(1, this.keys)+"\">首页</a></li>");	
        	  int prevPage=pageIndex-1;
        	  int nextPage=pageIndex+1;
        	  buf.append("<li class=\"prev "+(prevPage<1?"disabled":"")+"\" ><a href=\""+(prevPage<1?"javascript:?":this.createFullUrl(prevPage, this.keys))+"\">上一页</a></li>");	
          	  //中间页码
        	  int startIndex=(pageIndex-3)<=0?1:(pageIndex-3);
        	  int endIndex=(pageIndex+3)>pageCount?pageCount:(pageIndex+3);
        	  for(int p=startIndex;p<=endIndex;p++){
        		     buf.append("<li class=\"page "+(p==pageIndex?"active":"")+"\" ><a href=\""+this.createFullUrl(p, this.keys)+"\">"+p+"</a></li>");
        	  } 
        	  	buf.append("<li class=\"next "+(nextPage>pageCount?"disabled":"")+"\" ><a href=\""+(nextPage>pageCount?"javascript:?":this.createFullUrl(nextPage, this.keys))+"\">下一页</a></li>");	
        	    buf.append("<li class=\"last\" ><a href=\""+this.createFullUrl(this.pageCount, this.keys)+"\">尾页</a></li>");	
        	    this.keys.remove("pageIndex");
        	    buf.append("<li class=\"pageCount\">到<input style=\"width: 60px;padding: 0px 4px;\" type=\"text\" id=\"go\" value=\""+this.pageIndex+"\"  />页<button style=\"margin-top: -4px;\" class=\"btn btn-primary btn-sm\" onclick=\"javascript:if(document.getElementById('go').value.match(/^([0-9])*$/)&&parseInt(document.getElementById('go').value)<="+this.pageCount+") {window.location='"+this.url+"?pageIndex=__PAGE__&"+this.createParamUrl(this.keys)+"'.replace('__PAGE__',document.getElementById('go').value);} else {return false;}\">确定</button>");
        	    buf.append("共"+this.pageCount+"页</li>");
        	    buf.append("</ul>");
        	 
                return buf.toString();
        }
       return "";
        

    }
}